'use strict';
const db = uniCloud.database();

exports.main = async (event, context) => {
  const { article_id, user_id, content, user_name } = event;

  if (!article_id || !user_id || !content || !user_name) {
    return {
      code: -1,
      message: '缺少必要的参数'
    };
  }

  try {
    // 插入新评论
    await db.collection('comments').add({
      article_id: article_id,
      user_id: user_id,
      user_name: user_name,
      content: content,
      timestamp: Date.now()
    });

    // 更新文章的评论数量
    await db.collection('articles').doc(article_id).update({
      comment_count: db.command.inc(1)
    });

    return {
      code: 200,
      message: '评论成功',
      data: {
        status: 'success'
      }
    };
  } catch (error) {
    console.error(error);
    return {
      code: -1,
      message: '评论失败'
    };
  }
};
